package com.caigou.controller;

import com.alibaba.fastjson.JSON;
import com.caigou.bean.cms.entity.*;
import com.caigou.bean.cms.param.ArticlePreviewParam;
import com.caigou.pojo.*;
import com.caigou.service.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@Slf4j
public class ArticlePreviewController {

    @Resource
    private ArticleService articleService;

    @Resource
    private ArticlePromoterService articlePromoterService;

    @Resource
    private ChannelService channelService;

    @Resource
    private FriendshipLinkService friendshipLinkService;

    @Resource
    private CopyrightService copyrightService;

    @Value("${domain}")
    private String domain;
    @Value("${domainJunDui}")
    private String domainJunDui;
    @Value("${domainQiChe}")
    private String domainQiChe;
    @Value("${domainIT}")
    private String domainIT;
    @Value("${domainKongTiao}")
    private String domainKongTiao;
    @Value("${domainDianTi}")
    private String domainDianTi;
    @Value("${domainJiaJu}")
    private String domainJiaJu;
    @Value("${domainHuBei}")
    private String domainHuBei;



    @RequestMapping("/preview")
    public String preview(ModelMap model, HttpServletRequest request){
        String jsonStr = request.getParameter("jsonStr");
        log.info("jsonStr="+jsonStr);
        ArticlePreviewParam param = JSON.parseObject(jsonStr, ArticlePreviewParam.class);

        Map<String, Object> data = new HashMap<>();// 数据字段
        // 获取碎片信息
        data.put("domain", domain);// 域名属性
        data.put("domainJunDui", domainJunDui);//军队二级域名
        data.put("domainQiChe", domainQiChe);
        data.put("domainIT", domainIT);
        data.put("domainKongTiao", domainKongTiao);
        data.put("domainDianTi", domainDianTi);
        data.put("domainJiaJu", domainJiaJu);
        data.put("domainHuBei", domainHuBei);

        data.put("hibuick", "");// 官微
        data.put("hotSearch", "");// 热搜排行
        data.put("hotSpecial", "");// 热点专题
        data.put("videoClassroom", "");// 视频课堂
        data.put("excellentBooks", "");// 精品好书
        data.put("rightAd", "");// 广告位
        data.put("recommendArticle", "");// 猜你喜欢(不做)
        data.put("channelName", "");// 频道名称
        data.put("channelUrl", "");// 频道名称
        data.put("columnUrl", "");// 栏目名称

        //向preview*.ftl添加数据
        this.addArticleData(data, param);

        //header.ftl需要的数据
        this.addHeaderData(data);

        //添加character-card.ftl需要的数据
        this.addArticlePromoterData(data, param);

        //copyright.ftl需要的数据
        this.addCopyrightData(data);

        //footer.ftl需要的数据
        this.addFooterData(data);

        model.addAllAttributes(data);
        int articleType = param.getArticleType();
        if(articleType==1){//资讯
            return "/web/html/article/news/preview-news";
        }else if(articleType==2){//法律法规
            return "/web/html/article/law/preview-law";
        }else if(articleType==3){//案例点评
            return "/web/html/article/case/preview-case";
        }else if(articleType==4) {//图集资讯
            return "/web/html/article/album/preview-album";
        }else if(articleType==5||articleType==6){//亚利聊政采\政采周报(音频)
            return "/web/html/article/audio/preview-audio";
        }else if(articleType==7){//产品
            return "/web/html/article/news/preview-news";
        }else if(articleType==8){//图书
            return "/web/html/article/news/preview-news";
        }else if(articleType==14){//专题
            return "/web/html/article/special/preview-special";
        }else{
            return "/web/html/article/news/preview-news";
        }
    }

    private void addArticleData(Map<String, Object> data, ArticlePreviewParam param){
        // 判别内容字段--这个部分集合了文章底层页中各种类型文章的独有数据
        switch (param.getArticleType()) {// 判别正文显示类型/模板调用类型
            case 1://资讯
                data.put("articleContent", param.getArticleContent());// 文章新闻、内控制度、采购文件范本、采购合同范本、处理信息库(名库)、词库(政采百科)
                break;
            case 2:// 法律法规
                ArticleLaw articleLaw = param.getArticleLaw();
                data.put("articleLaw", articleLaw);
                List<ArticleDataEntryListData> list1 = articleLaw.getLawEntryList();// 获取第一层
                data.put("articleLawEntryList", list1);
                break;
            case 3:// 案例点评
                List<ArticleCaseData> articleCaseList = param.getArticleCase();
                data.put("articleCaseList", articleCaseList);
                break;
            case 4:// 图集资讯
                List<ArticleImageData> articleImageList = param.getArticleImage();
                data.put("articleImageList", articleImageList);
                break;
            case 5:// 政采周报(音频)
            case 6:// 亚利聊政采
                ArticleAudioData articleAudio = param.getArticleAudio();
                data.put("articleAudio", articleAudio);
                break;
            case 7:// 产品
                ArticleProductData articleProduct = param.getArticleProduct();
                data.put("articleContent", articleProduct.getProductContent());// 文章新闻、内控制度、采购文件范本、采购合同范本、处理信息库(名库)、词库(政采百科)
                break;
            case 8:// 图书
                ArticleBookData articleBook = param.getArticleBook();
                data.put("articleContent", articleBook.getBookContent());// 文章新闻、内控制度、采购文件范本、采购合同范本、处理信息库(名库)、词库(政采百科)
                break;
            case 14:// 专题
                // 设置专题是否有注释轴
                data.put("articleAnnotationStatus", param.getArticleAnnotationStatus());
                // 获取专题注释轴
                List<ArticleSpecialAnnotationData> annotationList = param.getArticleSpecialAnnotationList();
                data.put("annotationList", annotationList);
                // 获取专题配置数据
                List<ArticleSpecialLayoutData> layoutDataList = param.getArticleSpecialLayoutList();
                // 取出前两条作为单独数组
                ArticleSpecialLayoutData layoutDataList1;// Banner+标题
                ArticleSpecialLayoutData layoutDataList2;// 其余
                List<ArticleSpecialLayoutData> layoutDataList3 = new ArrayList<>();// 其余
                if (null != layoutDataList && layoutDataList.size() > 2) {
                    layoutDataList1 = layoutDataList.get(0);
                    layoutDataList2 = layoutDataList.get(1);
                    for (int i = 2; i < layoutDataList.size(); i++) {
                        layoutDataList3.add(layoutDataList.get(i));
                    }
                } else {
                    layoutDataList1 = layoutDataList.get(0);
                    layoutDataList2 = layoutDataList.get(1);
                }
                data.put("layoutDataList1", layoutDataList1.getArticleSpecialData().get(0));
                data.put("layoutDataList2", layoutDataList2.getArticleSpecialData().get(0));
                data.put("layoutDataList3", layoutDataList3);
                break;
            default:
                data.put("articleContent", param.getArticleContent());// 文章新闻、内控制度、采购文件范本、采购合同范本、处理信息库(名库)、词库(政采百科)
        }
        // 文章固定字段处理--这个部分集合了文章底层页中所有文章固有数据
        data.put("id", param.getArticleId());// 文章ID
        data.put("commentId", param.getArticleCommentId());// 评论ID
        data.put("commentStatus", param.getArticleCommentStatus());// 评论是否开启
        data.put("articleTitle", param.getArticleTitle());// 内文标题
        data.put("articleSource", param.getArticleSource());// 信息来源
        data.put("updateTime", new Date());// 发布时间
        data.put("createTime", new Date());// 创建时间(散列值)
        data.put("articleInfoStatus", param.getArticleInfoStatus());
        data.put("articleInfo", param.getArticleInfo());// 摘要(根据启用状态判别是否进行展示)
        data.put("articleShareImage", "");// 文章分享图
        // 作者列表处理
        List<ArticlePromoter> articleAuthorList = new ArrayList<>();
        if (param.getArticleAuthor()!=null && !param.getArticleAuthor().equals("")) {
            String[] articleAuthors = param.getArticleAuthor().split(",");
            for (String info : articleAuthors) {
                if(info.length()>0){
                    int intInfo = 0;
                    try{
                        intInfo = Integer.parseInt(info);
                        ArticlePromoter promoter = articlePromoterService.selectByPrimaryKey(intInfo);
                        if (null != promoter) {
                            articleAuthorList.add(promoter);
                        }
                    }catch (Exception e){
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        data.put("articleAuthorList", articleAuthorList);// 作者名字列表(数据处理)
        // 推荐作者
        data.put("articlePromoterStatus", param.getArticlePromoterStatus());// 是否启用作者推荐
        data.put("articleRecommendPromoter", param.getArticlePromoter());// 推荐作者的ID
        // 关键字列表处理
        List<ArticleKeyword> articleKeywordList = new ArrayList<>();// 关键词列表(可点击)
        List<String> keywords = new ArrayList<>();// 关键词列表(仅展示)
        if (!param.getArticleKeyWord().equals("")) {
            String[] articleKeyword = param.getArticleKeyWord().split(",");
            for (String info : articleKeyword) {
                ArticleKeyword keyword = articleService.selectKeywordByPrimaryKey(Integer.valueOf(info));
                if (null != keyword) {
                    articleKeywordList.add(keyword);
                    keywords.add(keyword.getKeyword());
                }
            }
        }
        data.put("articleKeywordList", articleKeywordList);// 关键词列表
        if (keywords.size() > 0) {
            data.put("keywords", String.join(",", keywords));// 关键词字符串(页头关键词字段)
        } else {
            data.put("keywords", "");// 关键词字符串(页头关键词字段)
        }
        // 附件列表
        data.put("adjunctList", param.getAdjunctList());// 附件列表
    }


    /**
     * 添加header.ftl需要的数据
     * @param data
     */
    private void addHeaderData(Map<String, Object> data){
        //header.ftl需要的数据
        String plateId = "101";
        HeaderConfig headerConfig = channelService.loadChannelHeaderConfig(plateId);// 获取头文件配置信息
        HeaderConfig phoneConfig = channelService.loadChannelHeaderConfig("100010601");// 获取全局手机二维码配置
        // 封装模板参数
        data.put("channelHomeUrl", headerConfig.getChannelUrl());// 当前频道首页链接地址
        log.info("---plateId={}, channelHomeUrl={}, channelName=---------", plateId, headerConfig.getChannelUrl(), headerConfig.getChannelName());
        data.put("channelLogo", headerConfig.getChannelLogo());// 频道log
        data.put("channelText", headerConfig.getChannelText());// 频道logAlt
        data.put("channelWeChatLogo", headerConfig.getChannelWeChatLogo());// 频道微信二维码
        data.put("channelWeChatText", headerConfig.getChannelWeChatText());// 频道微信展示文字
        data.put("siteLogo", phoneConfig.getSiteLogo());// 全局移动端手机二维码
        data.put("channelStatus", phoneConfig.getChannelStatus());// 全局移动端手机二维码状态
        data.put("channelDescription", phoneConfig.getChannelDescription());// 全局移动端手机二维码alt
        //data.put("header", "<!--#include virtual=\"/web/html/header/header.htm\"-->");
    }

    /**
     * 添加推荐作者character-card.ftl需要的数据
     * @param data
     */
    private void addArticlePromoterData(Map<String, Object> data, ArticlePreviewParam param){
        if(param.getArticlePromoterStatus()!=null && param.getArticlePromoterStatus()==1){
            ArticlePromoter articlePromoter = articlePromoterService.selectByPrimaryKey(param.getArticlePromoter());
            data.put("articlePromoterId", articlePromoter.getId());
            log.info("----------authorImage={}----------", articlePromoter.getAuthorImage());
            data.put("authorImage", articlePromoter.getAuthorImage());
            data.put("name", articlePromoter.getName());
            data.put("authorPost", articlePromoter.getAuthorPost());
            data.put("authorIntro", articlePromoter.getAuthorIntro());
            int articleCount = articleService.getArticleCountByArticlePromoter(articlePromoter.getId());
            data.put("articleCount", articleCount);
            List<Article> latestArticles = articleService.listLatestArticleByArticlePromoter(articlePromoter.getId());
            //构建关键词
            for(Article article:latestArticles){
                String keyword = article.getArticleKeyWord();
                if(keyword!=null&&keyword.length()>0){
                    String[] strings = keyword.split(",");
                    int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
                    List<ArticleKeyword> articleKeywords = articleService.findArticleKeywordsByIds(array);
                    article.setArticleKeywordList(articleKeywords);
                }
            }
            data.put("latestArticles", latestArticles);
        }
    }

    /**
     * 添加copyright.ftl需要的数据
     * @param data
     */
    private void addCopyrightData(Map<String, Object> data){
        String copyrightCode = "copyrightStatement";
        Copyright copyright = copyrightService.getCopyrightByCopyrightCode(copyrightCode);
        if(copyright!=null){
            data.put("copyrightValue", copyright.getCopyrightValue());
        }
        //data.put("copyright", "<!--#include virtual=\"/web/html/fragment/copyright/copyright.htm\"-->");
   }

    /**
     * 添加footer.ftl需要的数据
     * @param data
     */
    private void addFooterData(Map<String, Object> data){
        Page<?> page = PageHelper.startPage(1, 15);
        List<FriendshipLink> latestFriendshipLinks = friendshipLinkService.listFriendshipLink();
        HeaderConfig appConfig = channelService.loadChannelHeaderConfig("100011001");// 获取全局配置app下载二维码数据
        data.put("latestFriendshipLinks", latestFriendshipLinks);
        data.put("channelName", appConfig.getChannelName());
        data.put("siteLogo", appConfig.getSiteLogo());
        data.put("channelDescription", appConfig.getChannelDescription());
        //data.put("footer", "<!--#include virtual=\"/web/html/footer/footer.htm\"-->");
        //data.put("footer", "<#include \"/web/html/footer/footer.htm\"/>");
    }
}
